import React, { Component } from 'react'
import Header from "../../components/Header/Header"
import { reqgoodsinfo,reqcartadd } from "../../http/api"
import "./Detail.less"
import { $pre } from '../../http/http'
export default class Detail extends Component {
  constructor() {
    super()
    this.state = {
      //1.初始值
      arr: [],
    }
  }
  componentDidMount() {
    console.log(this.props.match.params.id);
    this.getdetail()
  }
  //请求列表
  async getdetail() {
    let res = await reqgoodsinfo({ id: this.props.match.params.id })
    if (res.data.code == 200) {
      let arr = res.data.list
      this.setState({
        arr: arr
      })
    }
  }
  tj(id) {
    reqcartadd({ goodsid: id, uid: JSON.parse(sessionStorage.getItem("userInfo")).uid,type:1,num:1 }).then(res=>{
      if (res.data.code==200) {
        alert("添加成功")
        console.log(this.props);
        this.props.history.push("/index/shop")
      }
    })
  }
  render() {
    let { arr } = this.state
    return (
      <div>
        <Header back title="商品详情"></Header>
        {
          arr.length > 0 ? arr.map(item => {
            return (
              <div className='card' key={item.id}>
                <img src={$pre + item.img} alt="" />
                <div className='right'>
                  <h3>商品名称:{item.goodsname}</h3>
                  <div>价格：{item.price}</div>
                  <button onClick={() => { this.tj(item.cateid) }}>加入购物车</button>
                </div>
              </div>
            )
          }) : <div>暂无数据</div>
        }
      </div>
    )
  }
}
